import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:yuan_hang_app/widget/w_dialog.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

class CallUtil {
  static call(context, phone, {onBack}) {
    showDialog(
        context: context,
        builder: (context1) => WDialog(
              context1,
              title: "提示",
              content: "你确定要拨打电话$phone吗？",
              onConfirm: (text) {
                callNumber(phone).then((res) {
                  holdUp(phone: phone, onBack: onBack);
                });
              },
            ));
  }

  static Future<void> callNumber(String phoneNumber) async {
    const platform = MethodChannel('cn.jtkj.yh_car_app/telephony');
    try {
      await platform
          .invokeMethod('dialPhoneNumber', {'phoneNumber': phoneNumber});
    } on PlatformException catch (e) {
      print("Failed to invoke: '${e.message}'.");
      Toast.toast("无法拨打电话");
    }
  }

  static Future<void> callNumber2(String phoneNumber) async {
    final Uri tel = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    if (!await launchUrl(tel)) {
      Toast.toast("无法拨打电话");
    }
  }

  // static void holdUp({phone, onBack}) {
  //   Timer? timer;
  //   int seconds = 0;
  //   const holdChannel = MethodChannel('cn.jtkj.yh_car_app/holdUp');
  //   holdChannel.setMethodCallHandler((MethodCall call) async {
  //     if (call.method == 'onTelephonyEvent') {
  //       Map params = call.arguments;
  //       String event = params["msg"].toString();
  //       if (event == 'call_up') {
  //         // 电话挂断，处理你的逻辑
  //         timer?.cancel();
  //         if (onBack != null) {
  //           onBack(params["duration"] != -1 ? params["duration"]! : seconds);
  //         }
  //       } else if (event == 'call_hold') {
  //         const oneSec = Duration(seconds: 1);
  //         timer = Timer.periodic(oneSec, (Timer timer) {
  //           seconds++;
  //           print("seconds: ${seconds}");
  //         });
  //       }
  //     }
  //   });
  // }

  static void holdUp({phone, onBack}) {
    int seconds = 0;
    DateTime startTime = DateTime.now();
    DateTime endTime;

    const holdChannel = MethodChannel('cn.jtkj.yh_car_app/holdUp');
    holdChannel.setMethodCallHandler((MethodCall call) async {
      if (call.method == 'onTelephonyEvent') {
        Map params = call.arguments;
        String event = params["msg"].toString();
        if (event == 'call_up') {
          // 电话挂断，处理你的逻辑
          endTime = DateTime.now();
          seconds = endTime.difference(startTime).inSeconds;
          if (onBack != null) {
            onBack(params["duration"] != -1 ? params["duration"]! : seconds);
          }
        } else if (event == 'call_hold') {
          startTime = DateTime.now();
        }
      }
    });
  }

  static Future<void> setBadgeNumber(int phoneNumber) async {
    const platform = MethodChannel('cn.jtkj.yh_car_app/bdgenumber');
    try {
      await platform.invokeMethod('setBadgeNumber', {'number': 1});
    } on PlatformException catch (e) {
      print("Failed to invoke: '${e.message}'.");

    }
  }
}
